﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Web;

namespace NewsSevicer
{
        public class WebSocketServer
        {
            private HttpListener _httpListener;
            private ConcurrentDictionary<string, WebSocket> _clients = new ConcurrentDictionary<string, WebSocket>();

            // 启动服务器
            public async Task StartAsync()
            {
                _httpListener = new HttpListener();
                _httpListener.Prefixes.Add("http://127.0.0.1:5009/");

                _httpListener.Start();
                Console.WriteLine("WebSocket服务器在ws://127.0.0.1:5009启动/");

                while (true)
                {
                    try
                    {
                        var context = await _httpListener.GetContextAsync();
                        if (context.Request.IsWebSocketRequest)
                        {
                            var webSocketContext = await context.AcceptWebSocketAsync(null);
                            var webSocket = webSocketContext.WebSocket;
                            var clientId = Guid.NewGuid().ToString(); // 使用客户端ID（例如GUID）来标识客户端
                            _clients[clientId] = webSocket;
                        // 解析 URL 获取 `username`
                        string username = "Guest"; // 默认用户名
                        var queryParams = HttpUtility.ParseQueryString(context.Request.Url.Query);
                        if (queryParams["username"] != null)
                        {
                            username = queryParams["username"];
                        }

                        Console.WriteLine($"客户端：  {clientId} 已连接....");

                            _ = Task.Run(() => HandleWebSocketAsync(clientId, webSocket ,  username)); // 异步处理客户端连接
                        }
                        else
                        {
                            context.Response.StatusCode = 400;
                            context.Response.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error accepting WebSocket connection: {ex.Message}");
                    }
                }
            }

            // 处理客户端消息
            private async Task HandleWebSocketAsync(string clientId, WebSocket webSocket,string username)
            {
                var buffer = new byte[1024];
                var cancellationToken = CancellationToken.None;
                var user = username;
                try
                {
                    while (webSocket.State == WebSocketState.Open)
                    {
                        var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken);

                        if (result.MessageType == WebSocketMessageType.Text)
                        {
                            string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
                            Console.WriteLine($"Received message from {clientId}: {message}");

                            // 解析消息，假设消息格式是 "TO:<targetClientId>:<message>"
                            string[] parts = message.Split(':');
                            if (parts.Length > 1 && parts[0] == "TO")
                            {
                                string targetClientId = parts[1]; // 获取目标客户端ID
                                string content = string.Join(":", parts, 2, parts.Length - 2); // 获取消息内容

                                // 如果目标客户端存在，则转发消息
                                if (_clients.TryGetValue(targetClientId, out WebSocket targetWebSocket))
                                {
                                    byte[] responseMessage = Encoding.UTF8.GetBytes(content);
                                    await targetWebSocket.SendAsync(new ArraySegment<byte>(responseMessage), WebSocketMessageType.Text, true, cancellationToken);
                                    Console.WriteLine($"Message sent to {targetClientId}: {content}");
                                }
                                else
                                {
                                    // 如果目标客户端不存在，返回错误消息
                                    byte[] errorMessage = Encoding.UTF8.GetBytes($"Client {targetClientId} not found.");
                                    await webSocket.SendAsync(new ArraySegment<byte>(errorMessage), WebSocketMessageType.Text, true, cancellationToken);
                                }
                            }
                        }
                        else if (result.MessageType == WebSocketMessageType.Close)
                        {
                            // 客户端关闭连接
                            await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", cancellationToken);
                            _clients.TryRemove(clientId, out _);
                            Console.WriteLine($"Client {clientId} disconnected.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
